/** @odoo-module **/

import {ControlPanel} from "@web/search/control_panel/control_panel";
import { SearchBar } from "@web/search/search_bar/search_bar";
import { SearchModel } from "@web/search/search_model";

import {registry} from "@web/core/registry";
import {useService} from "@web/core/utils/hooks";
import { download } from "@web/core/network/download";
import {Component, onWillStart, onMounted, useChildSubEnv, useState, useRef} from "@odoo/owl";
const { DateTime } = luxon;

export class SReportProductionScheduleComponent extends Component {
    setup() {
        this.orm = useService("orm");

        this.stationData = useState([]);
        this.stationTaskLine = useState([]);

        this.stationId = null

        this.searchInput = useRef('input')
        this.state = useState({
            dateList: [],
            toDay: DateTime.now().toFormat("yyyy-MM-dd"),
            dateStr: '',
        });
        onWillStart(async () => {
            // await this.stationWIP();
            // await this.computeMaterialConsumptionList();
        });
        onMounted(async () => {
            await this.getStationLineReportData();
            // await this.computeMaterialConsumptionList();
        })
    }

    async getStationLineReportData() {
        const data = await this.orm.call(
            "s.mrp.task",
            "get_station_line_report_data",
            [this.stationId, this.state.dateStr]
        );

        const dateList = data.date_list
        this.state.dateList.splice(0, this.state.dateList.length, ...dateList)
        this.state.dateStr = data.s_date
        this.stationData.splice(0, this.stationData.length, ...data.station_data);
        this.stationTaskLine.splice(0, this.stationTaskLine.length, ...data.task_data);
    }

    async onClickDateStr(dateStr) {
        this.state.dateStr = dateStr
        await this.getStationLineReportData()
    }
    async clickStation(stationId) {
        this.stationId = stationId
         await this.getStationLineReportData()
    }

    getDomain() {
        if (this.searchInput.el.value){
            const searchInput = this.searchInput.el.value.trim()
            return ['|', ['product_id.name', 'ilike', searchInput], ['production_id.name', 'ilike', searchInput]]
        } else {
            return []
        }
    }

    async handleKeyDown(ev) {

         if (ev.key === "Enter") {
            ev.preventDefault();
            await this.stationWIP();
            await this.clickStation(this.stationId)
        }
    }
    async onDownload() {
        const url = "/download/sb/production/wip/report/excel";
        const data = {};
        await download({ url , data });
    }
}

SReportProductionScheduleComponent.template = "sb_plan.SReportProductionSchedule";
SReportProductionScheduleComponent.components = {
    ControlPanel,
    // SearchBar
};
registry.category("actions").add("s_report_production_schedule", SReportProductionScheduleComponent);